package pattern9.SerialThreadConfinement.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @创建人 liweijia
 * @创建时间 2022/7/31
 * @描述 程序的主要用途
 */
public class Main {

    private static int num = 100000;

    public static void main(String[] args) {
        // 线程池为1,各个线程一定串行执行，最后num一定为0
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        // 如果线程池大小超过1一定有线程不安全的问题
        executorService = Executors.newFixedThreadPool(20);

        // 一直提交任务
        for (int i = 0; i < 100000; i++) {
            executorService.submit(() -> {
                int myNum = num;
                myNum -= 1;
                num = myNum;
            });
        }

        // 等待执行完毕
        executorService.shutdown();
        while (!executorService.isTerminated()){}
        System.out.println("运行结束 num=" + num);
    }
}
